<template>
  <div class="login-qr">
    <p>打开<span>网易云手机端</span>扫码登录</p>
    <img :src="imgurl" alt="" srcset="">
    <div class="zhezhao" v-show="refresh" @click="getUpdateKey">
      <i class="el-icon-refresh-right"></i>
    </div>
    <p>状态:
      <span style="margin-left:6px">{{state}}</span>
    </p>

  </div>
</template>

<script>
import router from '@/router'
// const base64=''

export default {
    name:"LoginByQr",
    data() {
        return {
            refresh:false,
            // base64:'',
            qrkey:'',
            state:'等待扫码',
            imgurl:[]
        }
    },
    methods: {
      async getKey(){
        const res=await this.$API.reqGetQrKey()
        if(res.code==200){
          this.qrkey=res.data.unikey
          const result=await this.$API.reqCreateQr(res.data.unikey)
          if(result.code==200){
            this.imgurl='data:image/png;base64,'+result.data.qrimg.split(',')[1]
            this.checkKey()
          }
          else{
            this.$message.info({message:'二维码生成失败！'})
          }
        }
        else{
          this.$message.info({message:'请求报错！'})
        }
      },
      async checkKey(){
        // let that=this
           const res=await this.$API.reqCheckQr(this.qrkey)
            if(res.code==800) {
              this.refresh=true
              this.state=res.message
            }
            //800 为二维码过期 801 为等待扫码,802 为待确认,803 为授权登录成功(
            else if(res.code==801||res.code==802){
              this.state=res.message
              this.timer=window.setTimeout(async()=>{
                this.checkKey()
              },5000)
            }
            else if(res.code==803){
              this.state=res.message
              await this.$store.dispatch('login/userInfo').then(res=>{
                this.$bus.$emit('updateAvatar','')
                this.$bus.$emit('aboutUserAllInfo','')
                this.$router.push({name:'center'})
              })
            }       
      },
      async getUpdateKey(){
        await this.getKey()
        this.refresh=false
      }
    },
    beforeDestroy(){
      window.clearTimeout(this.timer)
    },
    mounted() {
      this.getKey()
    },
}
</script>
<style lang="less" scoped>
.login-qr{
  display: flex;
  position: relative;
  align-items: center;
  flex-direction: column;
  height: 220px;
  p{
    span{
      color: #7c7cef;
    }
    margin-top: 5px;
    font-size: 12px;
  }
  img{
    margin-top: 10px;
    width: 150px;
    height: 150px;
  }
  .zhezhao{
    position: absolute;
    top:30px;
    width: 150px;
    height: 153px;
    text-align: center;
    cursor: pointer;
    background-color: rgb(139, 137, 137);
    opacity: .7;
    i{
      color: red;
      font-size: 20px;
      font-weight: 700;
      line-height: 153px;
    }
  }
}
</style>